package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.enums.SyncStatusEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.cop.b.rest.service.ICopAttachementService;
import com.ibeeking.found.cop.b.rest.service.IFansChannelWelcomeService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.dos.FansWelcomeDO;
import com.ibeeking.found.cop.service.common.param.CopAttachementParam;
import com.ibeeking.found.cop.service.common.param.FansChannelWelcomeParam;

import com.ibeeking.found.cop.service.common.param.UniAttachParam;
import com.ibeeking.found.cop.service.common.query.CopAttachementQuery;
import com.ibeeking.found.cop.service.common.query.FansChannelWelcomeQuery;
import com.ibeeking.found.cop.service.common.vo.CopAttachementVO;
import com.ibeeking.found.cop.service.common.vo.FansChannelWelcomeVO;
import com.ibeeking.found.cop.service.common.vo.UniAttachVO;
import com.ibeeking.found.cop.service.mapper.FansWelcomeMapper;
import com.ibeeking.found.id.GenerateId;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpWelcomeMsg;
import me.chanjar.weixin.cp.bean.external.msg.Text;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName FansChannelWelcomeServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class FansChannelWelcomeServiceImpl extends ServiceImpl<FansWelcomeMapper, FansWelcomeDO> implements IFansChannelWelcomeService {

    @Resource
    private FansWelcomeMapper fansWelcomeMapper;

    @Resource
    private ICopAttachementService copAttachementServiceImpl;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    @Override
    public List<FansChannelWelcomeVO> list(FansChannelWelcomeQuery query) {
        List<FansWelcomeDO> entityDOS = fansWelcomeMapper.selectList(new LambdaQueryWrapper<FansWelcomeDO>()
                .eq(query.getId() != null, FansWelcomeDO::getId, query.getId())
                .eq(FansWelcomeDO::getType, 1)
                .like(StringUtils.isNotBlank(query.getContent()), FansWelcomeDO::getContent, query.getContent())
                .eq(query.getStatus() != null, FansWelcomeDO::getStatus, query.getStatus())
                .orderByDesc(FansWelcomeDO::getCreateTime)
        );
        List<FansChannelWelcomeVO> entityVOS =JsonUtils.jsonToList(entityDOS, FansChannelWelcomeVO.class);
        if(Collections3.isNotEmpty(entityVOS)) {
            List<Long> ids = entityVOS.stream().map(FansChannelWelcomeVO::getId).collect(Collectors.toList());
            CopAttachementQuery attachementQuery = new CopAttachementQuery();
            attachementQuery.setMessageIds(ids);
            List<CopAttachementVO> copAttachementVOS = copAttachementServiceImpl.list(attachementQuery);
            Map<Long, CopAttachementVO> copAttachementMap = Collections3.isNotEmpty(copAttachementVOS)?copAttachementVOS.stream().collect(Collectors.toMap(CopAttachementVO::getMessageId, x->x, (o, n) -> n)):null;

            entityVOS.forEach(x -> {
                x.setStatusDesc(PublishStatusEnum.getName(x.getStatus()));
                x.setSyncStatusDesc(SyncStatusEnum.getName(x.getSyncStatus()));
                CopAttachementVO copAttachementVO = copAttachementMap!=null && copAttachementMap.size()>0?copAttachementMap.get(x.getId()):null;
                if(copAttachementVO!=null){
                    List<UniAttachVO> uniAttachVOS = copAttachementServiceImpl.transerCopAttachementToUniAttachement(copAttachementVO);
                    x.setAttachements(uniAttachVOS);
                }
            });
        }
        return entityVOS;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(FansChannelWelcomeParam param) {
        FansWelcomeDO entityDO = BeanUtil.convertBean(param, FansWelcomeDO.class);
        Long id = GenerateId.generateId();
        entityDO.setId(id);
        entityDO.setType(1);
        entityDO.setSelected(0);
        entityDO.setSyncStatus(SyncStatusEnum.SYNC_NO.getValue());
        entityDO.setStatus(PublishStatusEnum.DISABLE.getValue());
        List<UniAttachParam> uniAttachParams = param.getAttachements();
        if(Collections3.isNotEmpty(uniAttachParams)){
            CopAttachementParam copAttachementParam = copAttachementServiceImpl.transerUniAttachementToCopAttachement(uniAttachParams);
            if(copAttachementParam!=null){
                copAttachementParam.setMessageId(id);
                copAttachementServiceImpl.add(copAttachementParam);
            }
        }
        entityDO.setCreateBy(UserUtils.getUserId());
        entityDO.setCreateTime(LocalDateTime.now());
        entityDO.setModifyTime(LocalDateTime.now());
        return fansWelcomeMapper.insert(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modify(FansChannelWelcomeParam param) {
        FansWelcomeDO entityDO = BeanUtil.convertBean(param, FansWelcomeDO.class);
        entityDO.setSyncStatus(SyncStatusEnum.SYNC_NO.getValue());
        entityDO.setType(1);
        entityDO.setSelected(0);
        List<UniAttachParam> uniAttachParams = param.getAttachements();
        if(Collections3.isNotEmpty(uniAttachParams)){
            CopAttachementParam copAttachementParam = copAttachementServiceImpl.transerUniAttachementToCopAttachement(uniAttachParams);
            if(copAttachementParam!=null){
                copAttachementParam.setMessageId(entityDO.getId());
                copAttachementServiceImpl.modify(copAttachementParam);
            }
        }
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        return fansWelcomeMapper.updateById(entityDO) > 0;
    }

    @Override
    public FansChannelWelcomeVO view(Long id) {
        FansWelcomeDO entityDO = fansWelcomeMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        FansChannelWelcomeVO entityVO = BeanUtil.convertBean(entityDO, FansChannelWelcomeVO.class);
        if(entityVO != null) {
            entityVO.setStatusDesc(PublishStatusEnum.getName(entityDO.getStatus()));
            entityVO.setSyncStatusDesc(SyncStatusEnum.getName(entityDO.getSyncStatus()));
            CopAttachementVO copAttachementVO = copAttachementServiceImpl.queryByMessageId(id);
            if(null != copAttachementVO) {
                List<UniAttachVO> uniAttachVOS = copAttachementServiceImpl.transerCopAttachementToUniAttachement(copAttachementVO);
                entityVO.setAttachements(uniAttachVOS);
            }
        }
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeStatus(Long id, Integer status) {
        FansWelcomeDO entityDO = fansWelcomeMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        entityDO.setStatus(status);
        entityDO.setType(1);
        entityDO.setModifyBy(UserUtils.getUserId());
        entityDO.setModifyTime(LocalDateTime.now());
        return fansWelcomeMapper.updateById(entityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean del(Long id) {
        FansWelcomeDO entityDO = fansWelcomeMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        copAttachementServiceImpl.delByMessageId(id);
        return fansWelcomeMapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer syncFansWelcomeToWxCp(Long id){
        String tenantId = UserUtils.getTenantId();
        FansWelcomeDO entityDO = fansWelcomeMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");

        WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(Long.valueOf(tenantId));
        WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
        if (wxCpConfigStorage == null) {
            throw new BusinessException("获取企微服务失败!");
        }
        WxCpExternalContactService wxCpExternalContactService = wxCpService.getExternalContactService();
        if (wxCpExternalContactService == null) throw new BusinessException("获取企微服务外部联系人服务!");
        try {
            WxCpWelcomeMsg wxCpWelcomeMsg = new WxCpWelcomeMsg();
            wxCpWelcomeMsg.setWelcomeCode("");
            me.chanjar.weixin.cp.bean.external.msg.Text contentText = new Text();
            contentText.setContent(entityDO.getContent());
            wxCpWelcomeMsg.setText(contentText);
            wxCpExternalContactService.sendWelcomeMsg(wxCpWelcomeMsg);
            entityDO.setSyncStatus(SyncStatusEnum.SYNC_YES.getValue());
        } catch (WxErrorException ex) {
            LogUtils.error("同步新客户欢迎语出错" + ex);
            entityDO.setSyncStatus(SyncStatusEnum.SYNC_NO.getValue());
        }

        if (entityDO != null) {
            fansWelcomeMapper.updateById(entityDO);
        }
        return 1;
    }

}
